package models

import (
	"fmt"
	"rongyy/src/app"
)

type AdminModel struct {
	BaseModel `xorm:"extends"`
	Username  string `json:"username"`
	Password  string `json:"password"`
	Role      string `json:"role"`
	//Sn        string `json:"sn"`
	Status   int    `json:"status"`
	Hospital string `json:"hospital" xorm:"-"`
}

func (sm *AdminModel) TableName() string {
	return "sys_admin"
}

type AdminPassReq struct {
	Id          int64  `json:"id"`
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password"`
	Hospital    string `json:"hospital"`
}

//	func (rm *DoctorInfo) GetDoctorByIdM(sn string) (*DoctorInfo, bool, error) {
//	 doc := &DoctorInfo{}
//	 has, err := app.DB().Table("sys_employee").Where("sn = ? and del = 0", sn).Get(doc)
//	 if err != nil {
//	   return nil, false, err
//	 }
//	 return doc, has, err
//	}
func (am *AdminModel) Query(limit int, offset int) ([]AdminModel, int64, error) {
	ams := make([]AdminModel, 0)
	total, err := app.DB().Table("sys_admin").Where("role != 'super_admin'").Limit(limit, offset).FindAndCount(&ams)
	if err != nil {
		return nil, 0, err
	}
	return ams, total, err
}

//	func (rm *DoctorInfo) QueryBatch(limit int, offset int) ([]DoctorInfo, int64, error) {
//	 doc := make([]DoctorInfo, 0)
//	 total, err := app.DB().Table("sys_employee").Where("del = 0  and image !=''").Limit(limit, offset).FindAndCount(&doc)
//	 if err != nil {
//	   return nil, 0, err
//	 }
//	 return doc, total, err
//	}
func (sm *AdminModel) SignIn() (*AdminModel, error) {
	am := &AdminModel{}
	has, err := app.DB().Where("username = ? and password = ? and status = 0", sm.Username, sm.Password).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, fmt.Errorf("账号密码错误")
	}
	return am, nil
}

func (sm *AdminModel) GetById() (*AdminModel, error) {
	am := &AdminModel{}
	has, err := app.DB().ID(sm.Id).Where("status = 0").Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, fmt.Errorf("账号密码错误")
	}
	return am, err
}

func (sm *AdminModel) FindByUsername(username string) (*AdminModel, bool, error) {
	am := &AdminModel{}
	has, err := app.DB().Where("username = ?", username).Get(am)
	if err != nil {
		return nil, false, err
	}
	return am, has, err
}

func (sm *AdminModel) Insert() error {
	_, err := app.DB().Insert(sm)
	if err != nil {
		return err
	}
	return nil
}

func (sm *AdminModel) ChangePass(req *AdminPassReq) error {
	nsm := &AdminModel{}
	has, err := app.DB().Where("id = ? and password = ?", req.Id, req.OldPassword).Get(nsm)
	fmt.Println(has)
	if err != nil {
		return err
	}
	if !has {
		return fmt.Errorf("旧密码错误")
	}
	if req.NewPassword == "" {
		return fmt.Errorf("新密码违法")
	}
	nsm.Password = req.NewPassword
	_, err = app.DB().Where("id = ?", req.Id).Cols("password").Update(nsm)
	if err != nil {
		return err
	}
	return err
}
